package main

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
	"github.com/robfig/cron/v3"
	"net/url"
)

var globalC = cron.New(cron.WithSeconds())
var eid cron.EntryID
var cronTxt string = "0 0 0/1 * * ?"

func NewTop(w fyne.Window) *fyne.Container {
	box := container.NewHBox()

	cbt := widget.NewButton("每1小时", func() {
		cronTxt = "0 0 0/1 * * ?"
		//cronTxt = "0/20 * * * * ? "
	})

	cbt1 := widget.NewButton("每2小时", func() {
		cronTxt = "0 0 0/2 * * ?"
	})

	cbt2 := widget.NewButton("每4小时", func() {
		cronTxt = "0 0 0/4 * * ?"
	})

	cbt3 := widget.NewButton("每6小时", func() {
		cronTxt = "0 0 0/6 * * ?"
	})
	userEntry2 := widget.NewEntry()
	userL2 := widget.NewLabel("                           apikey                          ")

	box.Add(container.NewHBox(cbt, cbt1, cbt2, cbt3))
	box.Add(container.NewVBox(userL2, userEntry2))
	startbtn := widget.NewButton("开始", func() {
		if bc.State == 1 {
			dialog.NewInformation("", "正在运行，请先停止", w).Show()
			return
		}

		addFunc, err := globalC.AddFunc(cronTxt, func() {
			FetchList()
			bc.Log("开始执行")
			bc.NextLabel.SetText(globalC.Entry(eid).Next.Format("2006-01-02 15:04:05"))
			bc.StateLabel.SetText("运行中")
		})

		globalC.Start()

		if err != nil {
			dialog.NewInformation("tips", "表达式错误", w).Show()
			return
		}

		eid = addFunc

		entry := globalC.Entry(eid)

		bc.NextLabel.SetText(entry.Next.Format("2006-01-02 15:04:05"))
		bc.StateLabel.SetText("运行中")

		bc.Log("开始运行")

		bc.State = 1
	})

	stopbtn := widget.NewButton("停止", func() {
		globalC.Stop()
		bc.State = 0
		bc.StateLabel.SetText("停止")
		bc.NextLabel.SetText("")
		bc.Log("任务停止")
	})

	fetch := widget.NewButton("抓取", func() {
		FetchList()
	})

	label := widget.NewLabel("下次运行时间")
	nextTimeLable := widget.NewLabel("")
	bc.NextLabel = nextTimeLable

	timeLabel := container.NewHBox(label, nextTimeLable)

	state := widget.NewLabel("当前运行状态")
	stateLabel := widget.NewLabel("")

	stateVBox := container.NewVBox(state, stateLabel)

	bc.StateLabel = stateLabel

	box.Add(widget.NewSeparator())
	box.Add(startbtn)
	box.Add(stopbtn)
	box.Add(fetch)
	box.Add(stateVBox)
	box.Add(timeLabel)

	c := widget.NewButton("表达式帮助生成", func() {
		u, _ := url.Parse("https://cron.ciding.cc/")
		btcApp.OpenURL(u)
	})

	box.Add(c)
	userEntry2.SetText(setting.loanApiKey())
	bc.ApiKey = userEntry2
	return box
}
